<script setup>
import { ref } from "vue";
import { getListApi, createDataApi, updateDataApi, deleteDataApi, exportDataApi, readTableSearchApi, getSourceItemsApi } from "@/service/db.js";

// 分页组件
import CommonPagination from "@/components/pagination.vue";

// 通用表单组件
import CommonForm from "@/components/common-form.vue";

import { ElMessage } from "element-plus";
const table = ref("");
// 监听路由变化
import { useRoute } from "vue-router";

/****************************** 检索相关 ************************************************/
const filterForm = ref({});
const fileterItems = ref([]);
// 获取数据源数据
const getSourceItems = async field => {
	const res = await getSourceItemsApi({ table: field.DataSource });
	// 将res.data = [{id:'', title: ''}] 转换成 [{label: '', value: ''}]
	field.Options = res.data.map(item => {
		return {
			label: item.title,
			value: item.id
		};
	});
};

// 获取检索配置
const getFilterConfig = () => {
	readTableSearchApi({ table: table.value }).then(({ code, data, msg }) => {
		if (code !== 200) {
			// Alert 提示
			ElMessage.error(msg);
			return;
		}

		fileterItems.value = data;
		// 将fileterItems转换为ruleForm
		fileterItems.value.forEach(item => {
			filterForm.value[item.Field] = item.Default;
			// 获取数据源数据
			console.log(item);
			if (item.DataSource) {
				getSourceItems(item);
			}
		});
	});
};


/****************************** 列表相关 ************************************************/
const pagination = reactive({
	page: 1,
	limit: 15,
	total: 0
});

const tableData = ref([]);
const fields = ref([]);
const fetchList = async () => {
	let params = {
		table: table.value,
		...filterForm.value,
		pagination
	};
	const { code, data, msg } = await getListApi(params);

	if (code === 200) {
		tableData.value = data.list;
		fields.value = data.fields;
		pagination.total = data.pagination.total;
	} else {
		ElMessage.error(msg);
	}
};

// 搜索
const handleSearch = () => {
	pagination.page = 1;
	fetchList();
};

// 重置
const handleReset = () => {
	filterForm.value = {};
	pagination.page = 1;
	fetchList();
};

/****************************** 添加、编辑、删除 ************************************************/

// 删除状态
const handleDelete = row => {
	// 提示是否删除
	ElMessageBox.confirm("是否删除该状态?", "提示", {
		confirmButtonText: "确定",
		cancelButtonText: "取消",
		type: "warning"
	}).then(() => {
		deleteDataApi({ id: row.id }).then(res => {
			if (res.code === 200) {
				ElMessage.success("删除成功");
				fetchList();
			} else {
				ElMessage.error(res.msg);
			}
		});
	});
};

// 添加状态
const commonAddFormRef = ref(null);
const showAddForm = () => {
	commonAddFormRef.value.openDrawer("添加");
};

const handleAddSubmit = data => {
	data.table = table.value;
	createDataApi(data).then(({ code, msg }) => {
		if (code === 200) {
			ElMessage.success(msg);
			commonAddFormRef.value.closeDrawer();
			fetchList();
		} else {
			ElMessage.error(msg);
		}
	});
};

// 编辑状态
const commonEditFormRef = ref(null);
const showEditForm = row => {
	commonEditFormRef.value.openDrawer("编辑", row);
};

const handleEditSubmit = data => {
	data.table = table.value;
	updateDataApi(data).then(({ code, msg }) => {
		if (code === 200) {
			ElMessage.success(msg);
			commonEditFormRef.value.closeDrawer();
			fetchList();
		} else {
			ElMessage.error(msg);
		}
	});
};

// 导出
const handleExport = () => {
	let params = {
		table: table.value,
		...filterForm.value
	}
	exportDataApi(params).then(({ code, msg }) => {
		if (code === 200) {
			ElMessage.success(msg);
		} else {
			ElMessage.error(msg);
		}
	});
}

/****************************** 页面配置 ************************************************/

// 获取页面配置
const getPageConfig = () => {
	if (router.meta.table) {
		table.value = router.meta.table;
		// 获取检索配置
		getFilterConfig();
		fetchList();
	} else {
		ElMessage.error("未配置列表页");
	}
}

// 监听路由变化，获取页面配置
const router = useRoute();
watch(() => router.meta.table, (newVal) => {
	if (newVal) {
		getPageConfig();
	}
}, { immediate: true });
</script>

<template>
	<el-main>
		<div class="toolbar">
			<el-button type="warning" @click="showAddForm">添加</el-button>
			<el-form ref="ruleFromRef" :model="filterForm" inline>
				<el-form-item v-for="item in fileterItems" :key="item.Field">
					<el-input v-if="item.FormItemType === 'input'" v-model="filterForm[item.Field]"
						:placeholder="item.Placeholder"></el-input>

					<el-select v-else-if="item.FormItemType === 'select'" v-model="filterForm[item.Field]"
						:placeholder="item.Placeholder" clearable filterable>
						<el-option v-for="option in item.Options" :key="option.value" :label="option.label"
							:value="option.value"></el-option>
					</el-select>

					<el-radio-group v-else-if="item.FormItemType === 'radio'" v-model="filterForm[item.Field]">
						<el-radio v-for="option in item.Options" :key="option.value" :label="option.value">{{
							option.label
						}}</el-radio>
					</el-radio-group>

					<el-date-picker v-else-if="item.FormItemType === 'date'" v-model="filterForm[item.Field]"
						type="date" value-format="YYYY-MM-DD" :placeholder="item.Placeholder"></el-date-picker>

					<el-input v-else-if="item.FormItemType === 'textarea'" type="textarea"
						v-model="filterForm[item.Field]" :placeholder="item.Placeholder"></el-input>

					<el-switch v-else-if="item.FormItemType === 'switch'" v-model="filterForm[item.Field]"></el-switch>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="handleSearch">搜索</el-button>
					<el-button @click="handleReset">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<el-table class="list" :data="tableData" border style="width: 100%;overflow-x: auto;">
			<template v-for="item in fields" :key="item.Field">
				<el-table-column v-if="item.Width > 0" :label="item.Title" :align="item.Width > 0 ? 'center' : 'left'"
					:width="item.Width">
					<template #default="{ row }">
						<span v-if="item.Alias">
							{{ row[item.Alias]['title'] }}
						</span>
						<span v-else>
							{{ row[item.Field] }}
						</span>
					</template>
				</el-table-column>
				<el-table-column v-else :prop="item.Alias ? item.Alias['title'] : item.Field" :label="item.Title" :align="item.Width > 0 ? 'center' : 'left'"></el-table-column>
			</template>

			<el-table-column label="操作" width="200" align="center">
				<template #default="{ row }">
					<el-button type="primary" @click="showEditForm(row)">编辑</el-button>
					<el-button type="warning" @click="handleDelete(row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<div class="pagination">
			<div class="btn-group">
				<el-button type="primary" @click="handleExport">导出</el-button>
			</div>
			<common-pagination :pagination="pagination" @pagination-change="fetchList" />
		</div>

		<common-form ref="commonAddFormRef" @submit="handleAddSubmit" :table="table"></common-form>
		<common-form ref="commonEditFormRef" @submit="handleEditSubmit" :table="table"></common-form>
	</el-main>
</template>

<style scoped></style>
